import React from 'react';
import moment from 'moment';
import { Breadcrumb, Icon, Input, DatePicker, Button, Table, Checkbox, Modal, Select, Upload, message, Pagination, Form } from 'antd';
import './banner.less';
import $ from 'jquery';
import Config from '../../common/config';

const config = new Config();
const FormItem = Form.Item;
const token = sessionStorage.getItem('token');

//banner信息的表单
const BannerForm = Form.create()(
    (props) => {
        const { visible, saveBanner, handleCancel, form, normFile, beforeUpload, fileList, previewImg, previewVisible, cancelPreview, previewImage,colourNumber } = props;
        const { getFieldDecorator, getFieldValue } = form;
        const formItemLayout = { labelCol: { span: 6 }, wrapperCol: { span: 14 }, };
        return (
            <Modal
                className="banner-modal"
                title="banner管理"
                visible={visible}
                okText="保存"
                onOk={saveBanner}
                onCancel={handleCancel}
                maskClosable={false}
            >
                <Form layout="vertical">
                    <FormItem {...formItemLayout} label="活动名称" hasFeedback style={{ minHeight: '70px', marginBottom: 0 }}>
                        {getFieldDecorator('ActivityName', {
                            rules: [{ required: true, max: 10, message: '请输入活动名称，不超过10个字' }],
                        })(
                            <Input placeholder="请输入活动名称" />
                        )}
                    </FormItem>
                    <FormItem {...formItemLayout} label="链接地址" hasFeedback style={{ minHeight: '70px', marginBottom: 0 }}>
                        {getFieldDecorator('ImgURL', {
                            rules: [{ required: true, message: '请输入主题图片链接地址' }],
                        })(
                            <Input placeholder="请输入主题图片链接地址" />
                        )}
                    </FormItem>
                    <FormItem {...formItemLayout} label="颜色" hasFeedback style={{ minHeight: '70px', marginBottom: 0 }}>
                        {getFieldDecorator('colourNumber', {
                            rules: [{ required: true,min:3, message: '请输入颜色' }],
                        })(
                            <Input placeholder="请输入主题颜色" />
                        )}
                    </FormItem>

                    <FormItem {...formItemLayout} label="排序" hasFeedback style={{ minHeight: '70px', marginBottom: 0 }}>
                        {getFieldDecorator('Rank', {
                            rules: [{ required: true, pattern: /^\d{0,5}$/, message: '请输入数字，不超过99999' }],
                        })(
                            <Input placeholder="请输入图片排序，不超过99999" />
                        )}
                    </FormItem>
                    <FormItem {...formItemLayout} label="生效时间"  style={{ minHeight: '70px', marginBottom: 0 }}>
                        {getFieldDecorator('StartTime', {
                            rules: [{ type: 'object', message: '请选择生效时间' }],
                        })(
                            <DatePicker showTime format="YYYY-MM-DD HH:mm:ss" />
                        )}
                        <Checkbox style={{ marginLeft: "15px" }} disabled checked={getFieldValue('StartTime') ? true : false}>设定</Checkbox>
                    </FormItem>
                    <FormItem {...formItemLayout} label="过期时间"  style={{ minHeight: '70px', marginBottom: 0 }}>
                        {getFieldDecorator('EndTime', {
                            rules: [{ type: 'object', message: '请选择过期时间' }],
                        })(
                            <DatePicker showTime format="YYYY-MM-DD HH:mm:ss" />
                        )}
                        <Checkbox style={{ marginLeft: "15px" }} disabled checked={getFieldValue('EndTime') ? true : false}>设定</Checkbox>
                    </FormItem>
                    <FormItem {...formItemLayout} label="banner照片" style={{ minHeight: '120px', marginBottom: 0 }}>
                        <div>
                            {getFieldDecorator('Filedata', {
                                valuePropName: 'fileList', getValueFromEvent: normFile,
                                rules: [{ required: true, message: '请上传banner照片' }],
                            })(
                                <Upload
                                    accept="image/*"
                                    name="Filedata"
                                    action={config.UploadFile + "/uploadpageimg"}
                                    beforeUpload={beforeUpload}
                                    listType="picture-card"
                                    className="upload-list-inline"
                                    style={{ float: 'left' }}
                                    onPreview={previewImg}
                                >
                                    {
                                        fileList.length >= 1 ? null :
                                            <div>
                                                <Icon type="plus" />
                                                <div className="ant-upload-text">点击上传图片</div>
                                            </div>
                                    }
                                </Upload>
                            )}
                            <p style={{ float: 'left', width:'100%' }}>轮播图尺寸: 1200*400</p>
                        </div>
                    </FormItem>
                </Form>
                {/* 预览图片对话框 */}
                <Modal visible={previewVisible} footer={null} onCancel={cancelPreview}>
                    <img alt="example" style={{ width: '100%' }} src={previewImage} />
                </Modal>
            </Modal>
        );
    }
);
export default class Banner extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            bannerList: [],
            keyword: "",
            stime: "",
            pagesize: 10,
            pageindex: 1,
            bannercount: 1,
            visible: false,
            fileList: [],
            previewVisible: false,
            previewImage: '',
            BannerId: undefined,
        }
    }
    componentDidMount() {
        this.getBannerList();
    }
    //获取banner列表
    getBannerList() {
        $.ajax({
            url: `${config.JuseHomepage}/banner/list`,
            type: "get",
            async: true,
            headers: {
                'Authorization': 'Bearer ' + token,
            },
            data: {
                activityName: this.state.keyword,
                startTime: this.state.stime,
                pageSize: this.state.pagesize,
                page: this.state.pageindex
            },
            success: res => {
                if (res.code === 200) {
                    const bannerList = res.data.rows;
                    if (bannerList.length > 0) {
                        bannerList.forEach((ele, i) => {
                            ele.index = i + 1;
                        });
                        this.setState({
                            bannerList,
                            bannercount: res.data.count,
                        });
                    } else {
                        this.setState({
                            bannerList,
                            bannercount: res.data.count,
                        });
                    }
                }
            }
        });
    }
    // 分页显示
    changePage(pageindex) {
        this.setState({
            pageindex
        }, () => {
            this.getBannerList();
        });
    }
    //输入搜索关键字
    changeKeyword(e) {
        this.setState({
            keyword: e.target.value
        })
    }
    //选择有效时间
    changeStartTime(date, dateString) {
        this.setState({
            stimevalue: date,
            stime: dateString
        })
    }
    //搜索
    searchBanner() {
        this.setState({
            pageindex: 1
        }, () => this.getBannerList())
    }
    //重置
    clearSearch() {
        this.setState({
            keyword: "",
            stimevalue: null,
            stime: "",
            pageindex: 1
        }, () => {
            this.getBannerList()
        })
    }
    //刷新banner图状态
    // refreshStatus() {
    //     $.ajax({
    //         url: `${config.Homepage}/Banner/RefreshStatus`,
    //         type: "get",
    //         async: true,
    //         headers: {
    //             'Authorization': 'Bearer ' + token,
    //         },
    //         success: res => {
    //             if (res.status === 200) {
    //                 message.success(`刷新成功`, 2);
    //                 this.getBannerList();
    //             } else {
    //                 message.error(`刷新失败，请返回重新操作`, 2);
    //             }
    //         }
    //     });
    // }
    //banner详细信息对话框（新增/编辑）
    showBannerModal(record) {
        if (record) {
            const { fileList } = this.state;
            fileList[0] = {
                uid: -1,
                name: record.imgName,
                status: 'done',
                url: config.Filepath + record.imgName
            };
            this.bannerForm.setFieldsValue({
                ActivityName: record.activityName,
                ImgURL: record.imgURL,
                Rank: record.rank,
                StartTime: record.startTime ? moment(record.startTime) : null,
                EndTime: record.endTime ? moment(record.endTime) : null,
                Filedata: fileList,
                colourNumber:record.colourNumber,
            });
            this.setState({
                visible: true,
                fileList,
                BannerId: record.bannerId,
            });
        } else {
            this.setState({
                visible: true,
                BannerId: undefined
            });
        }
    }
    //保存
    saveBanner() {
        this.bannerForm.validateFields((err, values) => {
            if (!err) {
                const { BannerId } = this.state;
                let url,
                    data = {
                        activityName: values.ActivityName,
                        imgName: values.Filedata[0].response ? values.Filedata[0].response.name : values.Filedata[0].name,
                        imgURL: values.ImgURL,
                        rank: values.Rank,
                        startTime: values.StartTime ? values.StartTime.format('YYYY-MM-DD HH:mm:ss') : "",
                        endTime: values.EndTime ? values.EndTime.format('YYYY-MM-DD HH:mm:ss') : "",
                        colourNumber:values.colourNumber,
                    };
                if (BannerId) {
                    url = `${config.JuseHomepage}/banner/update`;
                    data.bannerId = BannerId;
                } else {
                    url = `${config.JuseHomepage}/banner/add`;
                }
                $.ajax({
                    url: url,
                    type: "post",
                    async: true,
                    headers: {
                        'Authorization': 'Bearer ' + token,
                    },
                    data: data,
                    success: res => {
                        if (res.code === 200) {
                            this.setState({
                                visible: false,
                                fileList: []
                            }, () => this.getBannerList())
                            this.bannerForm.resetFields();
                        } else if (res.code === 202) {
                            Modal.warning({
                                title: '保存失败',
                                content: `排序等级已存在,请另选一个排序等级`,
                            });
                        } else {
                            Modal.warning({
                                title: '保存失败',
                                content: `请返回重新操作`,
                            });
                        }
                    }
                });
            } else {
                message.error(`请填写必要的信息，再提交`, 2);
            }
        })
    }
    //取消，关闭对话框
    handleCancel() {
        this.bannerForm.resetFields();
        this.setState({
            visible: false,
            fileList: []
        });
    }
    //限制用户必须上传图片格式的文件、图片大小
    beforeUpload(file, fileList) {
        let isIMG = file.type.indexOf('image') != -1;
        if (!isIMG) {
            message.config({ top: 50 });
            message.error('您只能上传图片！');
        }
        let isLt10M = file.size / 1024 / 1024 < 10;
        if (!isLt10M) {
            message.config({ top: 50 });
            message.error('您上传的图片大小必须小于10MB！');
        }
        return isIMG && isLt10M;
    }
    //上传图片
    normFile(e) {
        this.setState({
            fileList: e.fileList
        });
        if (Array.isArray(e)) {
            return e;
        }
        return e && e.fileList;
    };
    //获取表单元素
    saveBannerFormRef(form) {
        this.bannerForm = form;
    }
    //预览图片对话框
    previewImg(file) {
        this.setState({
            previewImage: file.url || file.thumbUrl,
            previewVisible: true,
        });
    }
    //关闭预览图片对话框
    cancelPreview() {
        this.setState({ previewVisible: false })
    }
    render() {
        const columns = [{
            title: '序号',
            dataIndex: 'index',
            width: 50,
        }, {
            title: '排序',
            dataIndex: 'rank',
            width: 50,
        }, {
            title: '活动名称',
            dataIndex: 'activityName',
            width: 150,
        }, {
            title: '图片',
            dataIndex: 'imgName',
            render: (text, record) => (
                <a href={config.Filepath + record.imgName} target="_blank">
                    <img src={config.Filepath + record.imgName} style={{ height: "50px", width: "auto" }} />
                </a>
            ),
            width: 180,
        }, {
            title: '链接地址',
            dataIndex: 'imgURL',
            width: 200,
        }, {
            title: '生效时间',
            dataIndex: 'startTime',
            width: 130,
        }, {
            title: '过期时间',
            dataIndex: 'endTime',
            width: 130,
        }, {
            title: '状态',
            dataIndex: 'state',
            render: (text, record) => {
                if (text == 1) {
                    return <span>待展示</span>
                } else if (text == 2) {
                    return <span>展示中</span>
                } else {
                    return <span style={{ color: '#17D5DB' }}>已过期</span>
                }
            },
            width: 100,
        }, {
            title: '操作',
            key: 'edit',
            width: 50,
            render: (text, record) => (
                <span>
                    <a href="javascript:void(0);" onClick={() => this.showBannerModal(record)}>编辑</a>
                </span>
            )
        }];
        return (
            <div className="goods-label" style={{ minWidth: 1000 }}>
                <div className="goods-label-cont clearfix">
                    <div className='goods-label-cont-nav clearfix'>
                        <Breadcrumb separator=">">
                            <Breadcrumb.Item>首页</Breadcrumb.Item>
                            <Breadcrumb.Item><span className='separator-a'>Banner管理</span></Breadcrumb.Item>
                        </Breadcrumb>
                    </div>
                    <div className='spgl2-2 clearfix'>
                        <div className='member-content-Search'>
                            <div className='addetd'>
                                <Input className='addetd-a-r' addonBefore="活动名称" placeholder="请输入" value={this.state.keyword} onChange={(e) => this.changeKeyword(e)} />
                            </div>
                            <div className='addetd addetd1'>
                                <Input addonBefore="有效时间" />
                                <DatePicker onChange={this.changeStartTime.bind(this)} value={this.state.stimevalue} />
                            </div>
                            <Button type="primary" className='member-button' icon="search" onClick={() => this.searchBanner()}>搜索</Button>
                            <Button type="primary" className='member-button' icon="reload" onClick={() => this.clearSearch()}>重置</Button>
                            {/* <Button type="primary" className='member-button' icon="reload" onClick={() => this.refreshStatus()}>刷新状态</Button> */}
                            {/* <Button type="primary" className='member-button hons hons1'>首页生成</Button>
                            <Button type="primary" className='member-button hons'>首页预览</Button> */}
                        </div>
                    </div>

                    <div className='allgoods-table clearfix'>
                        <Table
                            className="floor-table"
                            rowKey="bannerId"
                            columns={columns}
                            dataSource={this.state.bannerList}
                            pagination={false}
                            bordered
                        />
                        <div className='goods-label-tabletr'>
                            <Button className='goods-label-table-app' width={160} icon="plus" onClick={() => this.showBannerModal()}>新增</Button>
                        </div>
                    </div>
                    <div className='goods-label-let'>
                        <div className="floor-ppagi">
                            {
                                this.state.bannercount == 0 ?
                                    <p className="floor-ppagip">
                                        共{this.state.bannercount}条记录
                                </p> :
                                    <p className="floor-ppagip">
                                        当前显示
                                    {this.state.pagesize * (this.state.pageindex - 1) + 1}—
                                    {this.state.pagesize * this.state.pageindex < this.state.bannercount ? this.state.pagesize * this.state.pageindex : this.state.bannercount}条记录，
                                    共{this.state.bannercount}条记录
                                </p>
                            }
                            <Pagination current={this.state.pageindex} total={this.state.bannercount || 1} defaultPageSize={this.state.pagesize} onChange={this.changePage.bind(this)} />
                        </div>
                    </div>
                    <BannerForm
                        visible={this.state.visible}
                        saveBanner={this.saveBanner.bind(this)}
                        handleCancel={this.handleCancel.bind(this)}
                        ref={this.saveBannerFormRef.bind(this)}
                        normFile={this.normFile.bind(this)}
                        beforeUpload={this.beforeUpload.bind(this)}
                        fileList={this.state.fileList}
                        previewImg={this.previewImg.bind(this)}
                        previewVisible={this.state.previewVisible}
                        cancelPreview={this.cancelPreview.bind(this)}
                        previewImage={this.state.previewImage}
                    />
                </div>
            </div>
        )
    }
}